﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace QLK.Database
{
    public class SupplierDAL
    {
        private ManageStoreDataContext ctx;

        public SupplierDAL()
        {
            ctx = new ManageStoreDataContext();
        }

        public Supplier GetSupplierBySupplierID(int supplierID)
        {
            Supplier curr = ctx.Suppliers.Single<Supplier>(supp => supp.SupplierID == supplierID);
            return curr;
        }

        public IEnumerable<Supplier> GetAllSupplier()
        {
            IEnumerable<Supplier> source = from supps in ctx.Suppliers
                                           orderby supps.SupplierName
                                           select supps;
            return source;
        }

        public bool DeleteSupplierBySupplierID(int supplierID)
        {
            Supplier curr = ctx.Suppliers.Single<Supplier>(supp => supp.SupplierID == supplierID);
            if (curr == null)
                return false;
            ctx.Suppliers.DeleteOnSubmit(curr);
            try
            {
                ctx.SubmitChanges();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }            
        }

        public bool CheckDuplicateSupplierBySupplierName(string supplierName)
        {
            Supplier curr = ctx.Suppliers.SingleOrDefault<Supplier>(supp => supp.SupplierName.Equals(supplierName));
            if (curr == null)
                return false;
            return true;
        }

        public bool UpdateSupplier(Supplier supplier)
        {
           Supplier curr = ctx.Suppliers.Single<Supplier>(supp => supp.SupplierID == supplier.SupplierID);

           if (curr == null)
                return false;
            curr.SupplierName = supplier.SupplierName;
            curr.Address = supplier.Address;
            curr.PhoneNumber = supplier.PhoneNumber;
            try
            {
                ctx.SubmitChanges();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }
        }

        public bool InsertSupplier(Supplier supplier)
        {           
            try
            {
                ctx.Suppliers.InsertOnSubmit(supplier);
                ctx.SubmitChanges();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }
        }


        //internal void DeleteSupplierBySupplierID(Supplier supp)
        //{
        //    throw new NotImplementedException();
        //}
    }
}
